package com.irun.pm.ui;

import java.io.File;
import java.util.Calendar;
import java.util.concurrent.Callable;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.irun.pm.R;
import com.irun.pm.controller.EnforcementControllers;
import com.irun.pm.interfaces.Callback;
import com.irun.pm.mode.DriverInfo;
import com.irun.pm.utils.FileUtils;
import com.irun.pm.utils.ImageUtil;
import com.irun.pm.utils.StringUtil;
import com.irun.pm.utils.TakePhotoUtils;
import com.irun.pm.utils.Utils;

/***
 * @author huangsm
 * @date 2012-5-27
 * @email huangsanm@gmail.com
 * @version 1.0
 * @description 录入现场执法信息
 */
public class SaveEnforcementActivity extends BaseActivity {

	private EditText mNativeAddress;
	private EditText mDate;
	private EditText mAddress;
	private EditText mCardNumber;
	private EditText mName;
	private EditText mSex;
	private EditText mCard;
	private EditText mDrive_age;
	private EditText mNotes;
	private EditText mResult;
	private EditText mDealPeople;
	
	private Button mBtn;
	private ImageView mPhoto;
	
	private Context mContext;
	private static final File PHOTO_DIR = new File(Environment
			.getExternalStorageDirectory()
			+ "/DCIM/Camera");
	private static final int REQUES_CAMERA = 0;
	private static final int DIALOG_EXIT = 1;
	private File mCurrentPhotoFile;
	private String mPath;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_enforcement);
		mContext = this;
		
		mNativeAddress = (EditText) findViewById(R.id.enf_native_address);
		mDate = (EditText) findViewById(R.id.enf_date);
		mDate.setOnClickListener(new EditText.OnClickListener() {
			@Override
			public void onClick(View v) {
				getDatePickerDialogForDate(mDate);
			}
		});
		mAddress = (EditText) findViewById(R.id.enf_address);
		mCardNumber = (EditText) findViewById(R.id.enf_card_numbe);
		mName = (EditText) findViewById(R.id.enf_name);
		mSex = (EditText) findViewById(R.id.enf_sex);
		mCard = (EditText) findViewById(R.id.enf_card);
		mDrive_age = (EditText) findViewById(R.id.enf_drive_age);
		mNotes = (EditText) findViewById(R.id.enf_note);
		mResult = (EditText) findViewById(R.id.enf_result);
		mDealPeople = (EditText) findViewById(R.id.enf_deal_people);
		mPhoto = (ImageView) findViewById(R.id.ivEnforPhoto);
		
		mPhoto.setOnClickListener(new ImageView.OnClickListener(){
			@Override
			public void onClick(View v) {
				TakePhotoUtils takePhotoUtils = new TakePhotoUtils(mContext);
				PHOTO_DIR.mkdirs();
				mCurrentPhotoFile = new File(PHOTO_DIR, TakePhotoUtils.getPhotoFileName());
				Intent intent = takePhotoUtils.doTakePhoto( mCurrentPhotoFile);
				startActivityForResult(intent, REQUES_CAMERA);
			}
		});
		mBtn = (Button) findViewById(R.id.btnSave);
		mBtn.setOnClickListener(new Button.OnClickListener(){
			@Override
			public void onClick(View v) {
				final String date = getStr(mDate);
				final String address = getStr(mAddress);
				final String name = getStr(mNativeAddress);
				final String card = getStr(mCard);
				if(StringUtil.isEmpty(name)){
					mNativeAddress.setError(Html
							.fromHtml("<font  color='black'>请填写事件名称</font>"));
					return;
				}
				if(StringUtil.isEmpty(date)){
					mDate.setError(Html
							.fromHtml("<font  color='black'>请填写事件发生时间</font>"));
					return;
				}
				if(StringUtil.isEmpty(address)){
					mAddress.setError(Html
							.fromHtml("<font  color='black'>请填写事件发生地点</font>"));
					return;
				}
				if(StringUtil.isEmpty(card)){
						mCard.setError(Html.fromHtml("<font  color='black'>请输入身份证号码</font>"));
						return;
				}
				if(!StringUtil.isEmpty(card)){
					if(card.length() < 15 || card.length() > 18){
						mCard.setError(Html.fromHtml("<font  color='black'>请填写15-18位身份证</font>"));
						return;
					}
				}
				doProgress("提示", "正在保存中...", new Callable<String>() {
					@Override
					public String call() throws Exception {
						Thread.sleep(2000);
						return null;
					}
				}, new Callback<String>() {
					@Override
					public void onCallback(String pCallbackValue) {
						// TODO Auto-generated method stub
						try{
							String nativeAddress = getStr(mNativeAddress);
							String car_number = getStr(mCardNumber);
							String sex = getStr(mSex);
							String card = getStr(mCard);
							String driverAge = getStr(mDrive_age);
							String notes = getStr(mNotes);
							String result = getStr(mResult);
							String dealPeople = getStr(mDealPeople);
							String name = getStr(mName);
							
							DriverInfo info = new DriverInfo();
							info.nativeAddress = nativeAddress;
							info.name = name;
							info.date = date.replace(" ", "#");
							info.address = address;
							info.cardNumber = car_number;
							info.name = name;
							info.sex = sex;
							info.card = card;
							info.driverAge = driverAge;
							info.note = notes;
							info.result = result;
							info.deal_people = dealPeople;
							info.photoPath = mPath;
							//DriverInfoControllers controllers = new DriverInfoControllers(mContext);
							EnforcementControllers controllers = new EnforcementControllers(mContext);
							String str = controllers.saveEnforcement(info);//.insertDriverInfo(info, Utils.TYPE_SITE_QUERY);
							System.out.println("str:" + result);
							if(str != null && str.equals("成功")){
								//Toast.makeText(mContext, "后台数据库无法连接，已成功暂存在本地!", Toast.LENGTH_SHORT).show();
								Toast.makeText(mContext, "数据保存成功！", Toast.LENGTH_LONG).show();
								setResult(Utils.ENFORCEMENT_RESULT_CODE);
								finish();
							}else{
								Toast.makeText(mContext, "数据保存失败，请检查您的网络连接！", Toast.LENGTH_SHORT).show();
							}
						}catch (Exception e) {
							e.printStackTrace();
						}
					}
				}, null);
				
				
				
			}
		});
		findViewById(R.id.btnPrint).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(mContext, "抱歉，暂时无法接入您的打印设备!", Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(resultCode == RESULT_CANCELED){
			return;
		}
		switch (requestCode) {
		case REQUES_CAMERA:
			Bitmap bmp = ImageUtil.compressHeadBitMap(mCurrentPhotoFile.getAbsolutePath());
			mPath = FileUtils.FILE_POLECE_IMAGE+TakePhotoUtils.getPhotoFileName();
			ImageUtil.saveBmp(bmp, FileUtils.FILE_POLECE_IMAGE+TakePhotoUtils.getPhotoFileName());
			mPhoto.setImageBitmap(bmp);
			break;
		default:
			break;
		}
	}
	
	/*//图片上传
	public void uploadFile(){
		String actionUrl = "";
	}*/
	
	@Override
	public void onBackPressed() {
		showDialog(DIALOG_EXIT);
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		AlertDialog dialog = null;
		switch (id) {
		case DIALOG_EXIT:
			dialog = new AlertDialog.Builder(this).setTitle("提示").setMessage("是否退出编辑?")
			.setPositiveButton("确定", new Dialog.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					SaveEnforcementActivity.this.finish();
				}
			}).setNegativeButton("取消", null).create();
			break;

		default:
			break;
		}
		return dialog;
	}
	
	private String getStr(EditText et){
		return et.getText().toString();
	}
	/**
	 * 获取日期
	 * @author huangsm
	 * @date 2012-5-26
	 * @email huangsanm@gmail.com
	 * @description
	 */
	private void getDatePickerDialogForDate(final EditText et){
		final Calendar cal = Calendar.getInstance();
		final int y = cal.get(Calendar.YEAR);
		final int mOfy = cal.get(Calendar.MONTH);
		final int dOfm = cal.get(Calendar.DAY_OF_MONTH);
		final int hourOfDay = cal.get(Calendar.HOUR_OF_DAY);
		final int minute = cal.get(Calendar.MINUTE);
		final 
		DatePickerDialog dpd = new DatePickerDialog(this, new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, final int year, final int monthOfYear, final int dayOfMonth) {
				new TimePickerDialog(mContext, new TimePickerDialog.OnTimeSetListener() {
					@Override
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						et.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth + " " + hourOfDay + ":" + minute);
					}
				}, hourOfDay, minute, true).show();
			}
		}, y, mOfy, dOfm);
		dpd.show();
	}
}
